# Create your views here.
from rest_framework.mixins import UpdateModelMixin

from utils.myModelViewSet import IsAuthenticatedViewSet
from .serializers import SimilarCharacterSerializer, ParentSerializer, ParentSerializerWithOriginImage
from variant_character.models import SimilarCharacter
from rest_framework import status
import logging
from rest_framework.response import Response

from fdfs_client.client import get_tracker_conf, Fdfs_client

tracker_path = get_tracker_conf('utils/fastdfs/client.conf')
client = Fdfs_client(tracker_path)
logger = logging.getLogger(__name__)


class SimilarCharacterViewSet(IsAuthenticatedViewSet):
    queryset = SimilarCharacter.objects.all()
    serializer_class = SimilarCharacterSerializer

    def create(self, request, *args, **kwargs):
        try:
            type_ = request.data['type']
        except:
            return Response({"msg": "请输入类型"})
        try:
            parent_id = request.data['parent_id']
        except:
            return Response({"msg": "请输入上一级id"})
        try:
            pinyin = request.data['pinyin']
        except:
            return Response({"msg": "请输入拼音字段"})
        try:
            image_path_label = request.data['image_path_label']
        except:
            return Response({"msg": "请输入图片定位路径"})
        if type_ == '1':
            try:
                word = request.data['word']
                image_url = ""
            except:
                return Response({"msg": "缺少字符"})
            if not pinyin:
                return Response(status=status.HTTP_400_BAD_REQUEST, data={"msg": "请您输入该异体字的拼音"})
        elif type_ == '2':
            if not pinyin:
                return Response({"msg": "请您输入该图片的拼音"})
            try:
                files = request.FILES.get('file')
            except:
                return Response({'msg': "请上传文件"})
            # 上传到FastDFS文件系统中
            image_ext_name = 'png'
            try:
                upload_res = client.upload_by_buffer(files.read(), file_ext_name=image_ext_name)
            except Exception as e:
                logger.error('异体字图片上传出现错误：{}'.format(e))
                return Response(status=status.HTTP_500_INTERNAL_SERVER_ERROR)
            else:
                if upload_res.get('Status') != 'Upload successed.':
                    return Response({'msg': '异体字图片上传失败，请稍后重试或联系管理员'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
                else:
                    image_url = upload_res.get('Remote file_id').decode()  # fastfds服务器返回的 图片路由
                    word = ""
        else:
            return Response({"msg": "非法类型"})
        request_data = {
            'word': word,
            'image_url': image_url,
            'type': type_,
            'parent_id': parent_id if parent_id else None,
            'reference': request.data.get("reference"),
            'image_path_label': image_path_label,
            'pinyin': pinyin
        }
        serializer = self.get_serializer(data=request_data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data)

    def update(self, request, *args, **kwargs):
        if request.data['type'] == '2':
            try:
                files = request.FILES.get('file')
                data = files.read()
            except:
                return Response(status=status.HTTP_400_BAD_REQUEST, data={'msg': "请上传文件"})
            # 上传到FastDFS文件系统中
            image_ext_name = 'png'
            try:
                upload_res = client.upload_by_buffer(data, file_ext_name=image_ext_name)
            except Exception as e:
                logger.error('异体字图片上传出现错误：{}'.format(e))
                return Response(status=status.HTTP_500_INTERNAL_SERVER_ERROR)
            else:
                if upload_res.get('Status') != 'Upload successed.':
                    return Response({'msg': '异体字图片上传失败，请稍后重试或联系管理员'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
                else:
                    image_url = upload_res.get('Remote file_id').decode()  # fastfds服务器返回的 图片路由
            request.POST._mutable = True
            request.data['image_url'] = image_url
        else:
            request.POST._mutable = True
            request.data['image_url'] = None
        return UpdateModelMixin.update(self, request, *args, **kwargs)

    def get_all_columns(self, request):
        char = SimilarCharacter.objects.filter(parent_id=None)
        serializer = ParentSerializer(char, many=True)
        return Response(serializer.data)

    def get_childrenOrparent(self, request, pk):
        data = SimilarCharacter.objects.filter(id=pk)
        if not data:
            return Response(status=status.HTTP_404_NOT_FOUND, data={'msg': "没有该异体字"})
        if not data[0].parent_id:
            data1 = ParentSerializerWithOriginImage(data,many=True)
            return Response(data1.data)
        else:
            data = SimilarCharacter.objects.filter(id=data[0].parent_id_id)
            data1 = ParentSerializerWithOriginImage(data,many=True)
            return Response(data1.data)
